#include "default_handler.h"

#include <stdio.h>

default_handler::default_handler( boost::asio::io_service *io) : _socket( new tcp::socket( *io ) )
{}

void default_handler::start()
{
	(*_socket).async_read_some( boost::asio::buffer( data, max_length ), 
								boost::bind( &default_handler::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) );
}

void default_handler::handle_read( const boost::system::error_code &error, uint32_t bytes_read )
{
	if( !error )
	{
		boost::asio::async_write( *_socket, 
								  boost::asio::buffer( data, bytes_read ), 
								  boost::bind( &default_handler::handle_write, this, boost::asio::placeholders::error ) );
	}
	else
	{
		printf( "Error reseting the socket\n" );
		delete this;
	}
}

void default_handler::handle_write( const boost::system::error_code &error )
{
	if( !error )
	{
		if( data[0] == 'q' )
		{
			printf( "Closing socket and reseting the socket\n" );
			delete this;
		}
		else
		{
			(*_socket).async_read_some( boost::asio::buffer( data, max_length ), 
									 boost::bind( &default_handler::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) );
		}
	}
	else
	{
		printf( "Error reseting the socket\n" );
		delete this;
	}
}

